package com.resource.animation
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	/**
	 * 管理资源的加载和缓存
	 */
	public class AnimationCacher extends EventDispatcher
	{
		private static var _instance:AnimationCacher;
		private var _cacher:Object = {};
		
		public function AnimationCacher()
		{
		}
		
		public static function getInstance():AnimationCacher{
			if(!_instance){
				_instance = new AnimationCacher;
			}
			return _instance;
		}
		
		public function getAnimation(url:String):Object{
			return _cacher[url];
		}
		
		public function load(url:String):void{
			var loader:AnimationLoader = new AnimationLoader;
			loader.url = url;
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(Event.COMPLETE, loadComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.load(new URLRequest(url));
		}
		
		private function loadComplete(event:Event):void{
			var loader:AnimationLoader = event.currentTarget as AnimationLoader;
			loader.removeEventListener(Event.COMPLETE, loadComplete);
			if(!_cacher[loader.url]){
				_cacher[loader.url] = AnimationDecoder.decode(loader.data as ByteArray);
			}
			var e:AnimationEvent = new AnimationEvent(loader.url);
			e.data = _cacher[loader.url];
			dispatchEvent(e);
		}
		
		private function onError(event:Event):void{
			var loader:AnimationLoader = event.currentTarget as AnimationLoader;
			loader.removeEventListener(Event.COMPLETE, loadComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			var e:AnimationError = new AnimationError(loader.url + "error");
			dispatchEvent(e);
		}
	}
}